package com.lzy.mall.search.service;

import cn.hutool.json.JSONUtil;
import com.lzy.mall.common.to.es.SkuEsModel;
import com.lzy.mall.search.config.ElasticConfig;
import com.lzy.mall.search.domain.EsConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author lzy
 * @date 2021/9/7 15:35
 */
@Service
@RequiredArgsConstructor(onConstructor_ = {@Autowired})
@Slf4j
public class ProductSaveService {

    private final RestHighLevelClient client;

    /**
     * 上架商品
     * @param skuEsModels
     */
    public void productStatusUp(List<SkuEsModel> skuEsModels) {
        //保存es
        //1.给es建立索引。product,建立好映射关系

        //2.给es中保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel esModel : skuEsModels) {
            IndexRequest request = new IndexRequest(EsConstant.PRODUCT_INDEX);
            request.id(esModel.getSkuId().toString());
            String json = JSONUtil.toJsonStr(esModel);
            request.source(json, XContentType.JSON);
            bulkRequest.add(request);
        }
        try {
            client.bulk(bulkRequest, ElasticConfig.COMMON_OPTIONS);
        } catch (IOException e) {
            log.info("es商品上架错误，原因：{}" + e);
            e.printStackTrace();
        }
        //TODO 批量操作错误处理

    }
}
